package com.shengong;

import java.util.Set;
import java.util.TreeMap;

/**
 * @ClassName Person
 * @Author shengong
 * @Date 2019-06-01 15:51
 * @Description 重写compareTo方法实现按年龄来排序
 *  Person对象没有实现Comparable接口，所以必须实现，才可以使用treeMap中的数据按顺序排列
 * String类、Integer类都已经实现了Comparable接口了
 *
 */
public class Person implements Comparable<Person>{

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int compareTo(Person o) {
        if(this.age > o.getAge()){
            return 1;
        }else if (this.age < o.getAge()){
            return -1;
        }
        return age;
    }

    public static void main(String[] args) {
        TreeMap<Person,String> data = new TreeMap<Person, String>();
        data.put(new Person("张三",30),"张三");
        data.put(new Person("李四",20),"李四");
        data.put(new Person("王五",10),"王五");
        data.put(new Person("小米",5),"小米");
        // 得到key值 同时得到key对应的值
        Set<Person> keys = data.keySet();
        for (Person key:keys){
            System.out.println(key.getAge()+"-"+key.getName());
        }

    }
}
